/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.threading;

import domain.DomainController;
import domain.net.HTMLParser;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.text.html.HTML.Attribute;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import persistence.net.Client;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 * Fetches the movie poster link from IMDB and uploads it to lulzimg.
 */
public class MoviePoster extends Thread
{
    private String movieName;

    /**
     * Constructor.
     * @param movieName The movie title.
     */
    public MoviePoster(String movieName)
    {
        this.movieName = movieName;
    }

    @Override
    public void run()
    {
        try
        {
            DomainController.getInstance().getUi().setButtonsEnabled(false);
            DomainController.getInstance().getUi().setStatusIndeterminate(true, "Fetching...");
        
            String rawMovieInfo = null;

            Client client = new Client();
            client.doGet("http://www.imdbapi.com/?i=&t=" + movieName.replaceAll(" ", "+"));

            rawMovieInfo = client.getResponseContent();
            JSONObject json = (JSONObject)JSONSerializer.toJSON(rawMovieInfo);

            //We want: Poster
            try
            {
                String posterURL = json.getString("Poster");

                DomainController.getInstance().getUi().setStatusIndeterminate(true, "Uploading...");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("uploadtype", "links"));
                nameValuePairs.add(new BasicNameValuePair("links", posterURL));
                nameValuePairs.add(new BasicNameValuePair("submit", ""));

                client.doPostUploadFile("http://lulzimg.com/upload.php", nameValuePairs, null);

                String content = client.getResponseContent();

                List<NameValuePair> results = HTMLParser.getTextAreaContentFrom(new StringReader(content),
                                                                                    Attribute.ID,
                                                                                    "imagecode1");

                String imageSrc = results.get(0).getValue();

                DomainController.getInstance().getLogger().log(Level.INFO, "Poster fetched and uploaded for movie \"{0}\".", movieName);

                DomainController.getInstance().getUi().insertTagInPostBody("[img]" + imageSrc + "[/img]");
            }
            catch(Exception e)
            {
                //No movie info...
                DomainController.getInstance().getUi().setStatusIndeterminate(false, "Done");
                String err = "No poster available for movie ";
                DomainController.getInstance().getLogger().log(Level.INFO, err + "\"{0}\".", movieName);
                DomainController.getInstance().fireMessage(err + movieName + ".", "Get and insert movie poster");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            DomainController.getInstance().getLogger().log(Level.SEVERE, "Error while trying to get movie poster. {0}", e.getMessage());
        }
        finally
        {
            DomainController.getInstance().getUi().setButtonsEnabled(true);
            DomainController.getInstance().getUi().setStatusIndeterminate(false, "Done");
        }
    }
}